/*
 * Description: 小数点精确几位
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/6/12 17:52
 */

export default {
  inserted(el, binding, vnode) {
    el.children[0].onblur = function() {
      const cur = binding.value && binding.value[binding.arg]

      if (cur === void 0 || cur === null || cur === '') return

      const modifiers = Object.keys(binding.modifiers)

      // 最小值
      let min = -Number.MAX_VALUE
      const minLabel = modifiers.find(m => m.indexOf('n') === 0)
      if (minLabel) {
        min = minLabel.split('n')[1]
        if (cur <= min) {
          return (binding.value[binding.arg] = min)
        }
      }
      const index = String(cur).indexOf('.')

      // 不存在小数点
      if (index === -1) return

      // 精度(默认精确7位)
      let precision = 7 + 1

      const precisionLabel = modifiers.find(m => m.indexOf('p') === 0)
      if (precisionLabel) {
        precision = precisionLabel.split('p')[1] + 1
      }

      return (binding.value[binding.arg] = String(cur).substr(0, index + precision))
    }
  }
}
